package ydd.yykj.dl.com.rxjavatest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;

public class MainActivity extends AppCompatActivity {
    TextView tv1;
    TextView tv2;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.tv1);
        tv2 = (TextView) findViewById(R.id.tv2);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Observable observable = createObservable();
                Subscriber subscriber = createSubscriber();
                tv2.append("开始订阅，准备观察...\n");
//                observable.subscribe(subscriber);
                observable.subscribe(new Action1<String>() {
                    @Override
                    public void call(String o) {
                        tv2.append("执行观察者中的onNext()...\n");
                        tv2.append(o+"...\n");
                    }
                });
            }
        });


    }

    private Observable createObservable(){
//        Observable observable = Observable.create(new Observable.OnSubscribe<String>(){
//            @Override
//            public void call(Subscriber<? super String> subscriber) {
//                subscriber.onNext("top");
//                subscriber.onNext("juggle");
//                subscriber.onNext("mid");
//                subscriber.onNext("support");
//                subscriber.onNext("adc");
//                subscriber.onCompleted();
//            }
//        });
        String[] datas = {"top","juggle","mid","support","adc"};
//        Observable observable = Observable.from(datas);
        Observable observable = Observable.just("top","juggle","mid","support","adc");
        return observable;
    }

    private Subscriber createSubscriber(){
        Subscriber subscriber = new Subscriber<String>(){

            @Override
            public void onCompleted() {
                tv2.append("执行观察者中的onCompleted()...\n");
                tv2.append("订阅完毕，结束观察...\n");
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                tv2.append("执行观察者中的onNext()...\n");
                tv2.append(s+"...\n");
            }
        };
        return subscriber;
    }
}
